package com.javadroid.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Looper;
import android.util.Log;

import com.javadroid.model.DicionarioDeDados;


public class OperacoesHTTP {
	
	
	public void enviaJsonParaOServer() throws JSONException, ClientProtocolException, IOException {

	    DefaultHttpClient httpClient = new DefaultHttpClient();
	    ResponseHandler <String> resonseHandler = new BasicResponseHandler();
	    HttpPost postMethod = new HttpPost(DicionarioDeDados.URL_TODOS_NOVELAS.getInformacao());
	    postMethod.setHeader( "Content-Type", "application/json" );
	    
	    JSONObject json = new JSONObject();
	    json.put("AlertEmail",true);
	    json.put("APIKey","abc123456789");
	    json.put("Id",0);
	    json.put("AlertPhone",false);      
	    postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
	    String response = httpClient.execute(postMethod,resonseHandler);
	    Log.e("response :", response);
	    }
	
	public void getJsonDoServer(){
		DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
		HttpPost httppost = new HttpPost(DicionarioDeDados.URL_TODOS_NOVELAS.getInformacao());
		// Depends on your web service
		httppost.setHeader("Content-type", "application/json");

		InputStream inputStream = null;
		try {
		    HttpResponse response = httpclient.execute(httppost);           
		    HttpEntity entity = response.getEntity();

		    inputStream = entity.getContent();
		    // json is UTF-8 by default
		    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
		    StringBuilder sb = new StringBuilder();

		    String line = null;
		    while ((line = reader.readLine()) != null){
		        sb.append(line + "\n");
		    }
		} catch (Exception e) { 
			String err = (e.getMessage()==null) ? "Erro Generico" : e.getMessage();
			Log.e(" SmartNovelas ",err); 
		}
		finally {
		    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
		}
	}

	protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(DicionarioDeDados.URL_TODOS_NOVELAS.getInformacao());
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        response.getEntity().getContent(); 
                    }

                } catch(Exception e) {
        			String err = (e.getMessage()==null) ? "Erro Generico" : e.getMessage();
        			Log.e(" SmartNovelas ",err); 

                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }
	public void postData(String url,JSONObject obj) {
	    // Create a new HttpClient and Post Header

	    HttpParams myParams = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
	    HttpConnectionParams.setSoTimeout(myParams, 10000);
	    HttpClient httpclient = new DefaultHttpClient(null);

	    try {

	        HttpPost httppost = new HttpPost(url.toString());
	        httppost.setHeader("Content-type", "application/json");

	        StringEntity se = new StringEntity(obj.toString()); 
	        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
	        httppost.setEntity(se); 

	        HttpResponse response = httpclient.execute(httppost);
	        String temp = EntityUtils.toString(response.getEntity());
	        Log.i("tag", temp);


	    } catch (ClientProtocolException e) {
			String err = (e.getMessage()==null) ? "Erro Generico" : e.getMessage();
			Log.e(" SmartNovelas ",err); 

	    } catch (IOException e) {
			String err = (e.getMessage()==null) ? "Erro de IO" : e.getMessage();
			Log.e(" SmartNovelas ",err); 

	    }
	}

}
